/**
 * @file tone.c
 * @brief COSC361 - MCU Jukebox Project\n
 * Group: Hamish Cumming, Brian Thorne\n
 * Latest source can be obtained using SVN from google's code repository with the following command:\n
 * svn checkout http://mega8-hob.googlecode.com/svn/trunk/ jukebox-hamish-brian\n
 * Description: Code relating to producing tones from the jukebox\n
 * Date: 25/5/2008
 */

#include "tone.h"
#include "spi.h"
#include "timer.h"

#define SCALE_X 256

/**
 * @brief The LUT for generating a sine wave
 */
const static int sinLUT[SCALE_X] = {128, 131, 134, 137, 140, 143, 146, 149, 153, 156, 159, 162, 
165, 168, 171, 174, 177, 180, 182, 185, 188, 191, 194, 196, 199, 201, 204, 207, 209, 
211, 214, 216, 218, 220, 223, 225, 227, 229, 231, 232, 234, 236, 238, 239, 241, 242, 
243, 245, 246, 247, 248, 249, 250, 251, 252, 253, 253, 254, 254, 255, 255, 255, 255, 
255, 255, 255, 255, 255, 255, 254, 254, 253, 253, 252, 251, 251, 250, 249, 248, 247, 
245, 244, 243, 241, 240, 238, 237, 235, 233, 232, 230, 228, 226, 224, 222, 219, 217, 
215, 213, 210, 208, 205, 203, 200, 198, 195, 192, 189, 187, 184, 181, 178, 175, 172, 
169, 166, 163, 160, 157, 154, 151, 148, 145, 142, 139, 135, 132, 129, 126, 123, 120, 
116, 113, 110, 107, 104, 101, 98, 95, 92, 89, 86, 83, 80, 77, 74, 71, 68, 66, 63, 60, 
57, 55, 52, 50, 47, 45, 42, 40, 38, 36, 33, 31, 29, 27, 25, 23, 22, 20, 18, 17, 15, 
14, 12, 11, 10, 8, 7, 6, 5, 4, 4, 3, 2, 2, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 
2, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 13, 14, 16, 17, 19, 21, 23, 24, 26, 28, 30, 32, 
35, 37, 39, 41, 44, 46, 48, 51, 54, 56, 59, 61, 64, 67, 70, 73, 75, 78, 81, 84, 87, 
90, 93, 96, 99, 102, 106, 109, 112, 115, 118, 121, 124, 127};

/**
 * @brief Output an array of tones to the DAC
 */
void play_tone(tone_t tone)
{

    unsigned int output=0;
    unsigned int pv = timer0_getCurrentValue();
    unsigned int a = tone.frequency / 2;
    if (pv > 2*a) { timer0_reset(); return;}
    output = sinLUT[(pv % a) * SCALE_X / a];
    SPI_transmitToDAC(output);
}
